package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction_lj;
import com.atguigu.bean.CourseInfoBean;
import com.atguigu.util.ClickHouseUtil_lj;
import com.atguigu.util.DateFormatUtil_lj;
import com.atguigu.util.MyKafkaUtil_lj;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author 晶晶   1.5.2 各课程交易统计  已跑通
 * @Date 2023 03 27 14 48
 **/
public class Dws_StudyCourse_Info {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        String topic = "dwd_test_exam";
        String groupId = "dws_study_course_info0926";
        DataStreamSource<String> kafkaDs = env.addSource(MyKafkaUtil_lj.getFinkKafkaConsumer(topic, groupId));

        //kafkaDs.print(">>>>>>>>>>>>>>>>>>");
        SingleOutputStreamOperator<JSONObject> jsonDs = kafkaDs.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //jsonDs.print(">>>>>>>>>>>>>>>>>");

        SingleOutputStreamOperator<JSONObject> dsWithWM = jsonDs.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                }));

        //keyedDs.print(">>>>>>>>>>>>>>");
        SingleOutputStreamOperator<CourseInfoBean> beanDs = dsWithWM.flatMap(new RichFlatMapFunction<JSONObject, CourseInfoBean>() {

            @Override
            public void flatMap(JSONObject value, Collector<CourseInfoBean> out) throws Exception {

                    HashSet<String> userIds = new HashSet<>();
                    userIds.add(value.getString("user_id"));

                    out.collect(CourseInfoBean.builder()
                            .paperId(value.getString("paper_id"))
                            .userIds(userIds)
                            .score(value.getLong("score"))
                            .durations(value.getLong("duration_sec"))
                            .build());
                }

        });

        //关联
        SingleOutputStreamOperator<CourseInfoBean> courseIdDs = AsyncDataStream.unorderedWait(beanDs, new AsyncDimFunction_lj<CourseInfoBean>("dim_test_paper".toUpperCase()) {
            @Override
            public String getKey(CourseInfoBean input) {
                //System.out.println(input.getPaperId());
                return input.getPaperId();
            }

            @Override
            public void join(CourseInfoBean input, JSONObject dimInfo) {
                input.setCourseId(dimInfo.getString("course_id".toUpperCase()));

            }
        }, 60, TimeUnit.SECONDS);

        //courseIdDs.print(">>>>>>>>>>>>>>>>>>");

        //分组 开窗 聚合
        SingleOutputStreamOperator<CourseInfoBean> resultDs = courseIdDs
                .keyBy(new KeySelector<CourseInfoBean, String>() {
                    @Override
                    public String getKey(CourseInfoBean value) throws Exception {
                        return value.getCourseId();
                    }
                })
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<CourseInfoBean>() {
                            @Override
                            public CourseInfoBean reduce(CourseInfoBean value1, CourseInfoBean value2) throws Exception {
                                Set<String> ids = value1.getUserIds();
                                ids.addAll(value2.getUserIds());
                                value1.setDurations(value1.getDurations() + value2.getDurations());
                                value1.setScore(value1.getScore()+value2.getScore());
                                value1.setUserIds(ids);
                                return value1;
                            }
                        },

                        new WindowFunction<CourseInfoBean, CourseInfoBean, String, TimeWindow>() {
                            @Override
                            public void apply(String s, TimeWindow window, Iterable<CourseInfoBean> input, Collector<CourseInfoBean> out) throws Exception {
                                for (CourseInfoBean next : input) {
                                    next.setStt(DateFormatUtil_lj.toYmdHms(window.getStart()));
                                    next.setEdt(DateFormatUtil_lj.toYmdHms(window.getEnd()));
                                    next.setTs(System.currentTimeMillis());

                                    next.setExamCount((long) next.getUserIds().size());
                                    next.setAvgScore((next.getScore() * 1D) / next.getUserIds().size());
                                    next.setAvgDuration((next.getDurations() * 1D) / next.getUserIds().size());

                                    out.collect(next);
                                }

                            }
                        }
                );

        //补充字段
        SingleOutputStreamOperator<CourseInfoBean> courseDs = AsyncDataStream.unorderedWait(resultDs, new AsyncDimFunction_lj<CourseInfoBean>("dim_course_info".toUpperCase()) {
            @Override
            public String getKey(CourseInfoBean input) {
                return input.getCourseId();
            }

            @Override
            public void join(CourseInfoBean input, JSONObject dimInfo) {
                input.setName(dimInfo.getString("course_name".toUpperCase()));
            }

        }, 60, TimeUnit.SECONDS);

        //写入clickhouse
        courseDs.print(">>>>>>>>>>>>>>>>>>>>>>");
        courseDs.addSink(ClickHouseUtil_lj.getClickHouseSink("insert into dws_study_course_info values(?,?,?,?,?,?,?,?)"));

        //运行任务
        env.execute("Dws_Study_course_Info");
    }
}
